import time

import serial
import serial.tools.list_ports
import binascii


class PortCommunication:
    def __init__(self, com, bps, timeout):
        self.port = com
        self.bps = bps
        self.timeout = timeout
        self.port_is_open = False
        try:
            # 打开串口，并得到串口对象
            self.used_port = serial.Serial(self.port, self.bps, timeout=self.timeout)
            # 判断是否打开成功
            self.check_port_state()
            self.port_is_open = True
        except Exception as e:
            print("port init error：", e)

    # 检查端口状态
    def check_port_state(self):
        if self.used_port.is_open:
            print("------------Port Init----------------")
            print('The port is ready.')
        else:
            print('the port is not open!')

    # 打印设备基本信息
    def print_port_info(self):
        print('name: ' + self.used_port.name)  # 设备名字
        print('port: ' + self.used_port.port)  # 读或者写端口
        print('baudrate: ' + str(self.used_port.baudrate))  # 波特率
        print('bytesize: ' + str(self.used_port.bytesize))  # 字节大小
        print('parity: ' + str(self.used_port.parity))  # 校验位
        print('stopbits: ' + str(self.used_port.stopbits))  # 停止位
        print('timeout: ' + str(self.used_port.timeout))  # 读超时设置
        print('writeTimeout: ' + str(self.used_port.writeTimeout))  # 写超时
        print('xonxoff: ' + str(self.used_port.xonxoff))  # 软件流控
        print('rtscts: ' + str(self.used_port.rtscts))  # 软件流控
        print('dsrdtr: ' + str(self.used_port.dsrdtr))  # 硬件流控
        print('interCharTimeout: ' + str(self.used_port.interCharTimeout))  # 字符间隔超时

    # 打开串口
    def open_port(self):
        if not self.used_port.is_open:
            self.used_port.open()
            self.check_port_state()

    # 关闭串口
    def close_port(self):
        self.used_port.close()
        print('The port is closed.')  # 检验串口是否打开

    # 发数据
    def send_data(self, data):
        self.used_port.write(data)
        time.sleep(0.8)

    def read_data(self):
        # count = self.used_port.inWaiting()
        self.used_port.flush()
        return self.used_port.readlines()

    def port_clear(self):
        self.used_port.flushInput()
        self.used_port.flushOutput()

